package com.bw.crop.controller;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.crop.domain.*;
import com.bw.crop.service.*;
import com.ruoyi.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("outbound")
public class OutboundController {
    @Autowired
    SysTradesmanService tradesmanService;
    @Autowired
    SysTransportService transportService;
    @Autowired
    SysTransportTradesmanService transportTradesmanService;
    @Autowired
    SysCropStashService cropStashService;
    @Autowired
    SysProductProcessingService processingService;
    @Autowired
    SysStashsService sysStashsService;
    @Autowired
    SysCropStashService sysCropStashService;
    @Autowired
    private TdtranceService tdtranceService;
    @Autowired
    private SysLogsWarehouseService logsWarehouseService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 添加物流
     * @param sysTransport
     * @return
     */
    @RequestMapping("transportAdd")
    @Transactional
    public R transportAdd(@RequestBody SysTransport sysTransport){
        Integer oneNum = sysCropStashService.getOneNum(sysTransport.getCname(),sysTransport.getFsid(),sysTransport.getSid());
        if (oneNum>=sysTransport.getNum()){
            List<SysCropStash> numList = sysCropStashService.getNumList(sysTransport.getCname(),sysTransport.getSid(),sysTransport.getFsid());
            int num=sysTransport.getNum();
            for (SysCropStash cropStash : numList) {
                if (num<=0){
                    break;
                }
                if (num>=cropStash.getNum()){
                    SysTransport addtrop = addtrop(sysTransport);
                    addtrop.setCropId(cropStash.getCropId());
                    addtrop.setNum(cropStash.getNum());
                    transportService.save(addtrop);
                    //出庫記錄
                    SysLogsWarehouse logsWarehouse = new SysLogsWarehouse();
                    logsWarehouse.setOutInWarehouse(1);
                    logsWarehouse.setFstashId(sysTransport.getFsid());
                    logsWarehouse.setStashId(sysTransport.getSid());
                    logsWarehouse.setCreateDate(new Date());
                    logsWarehouse.setInFromTo(sysTransport.getEndAddress());
                    logsWarehouse.setOutInSum(addtrop.getNum());
                    logsWarehouse.setOutInGoods(sysTransport.getCname());
                    //获取登录人
                    Map getuser = getuser();
                    logsWarehouse.setOutInUser(getuser.get("name").toString());
                    logsWarehouseService.save(logsWarehouse);
                    num=num-cropStash.getNum();
                    cropStash.setNum(0);
                    sysCropStashService.updateById(cropStash);
                }else {
                    SysTransport addtrop = addtrop(sysTransport);
                    addtrop.setCropId(cropStash.getCropId());
                    addtrop.setNum(num);
                    transportService.save(addtrop);
                    cropStash.setNum(cropStash.getNum()-num);
                    sysCropStashService.updateById(cropStash);
                    num=0;
                    //出庫記錄
                    SysLogsWarehouse logsWarehouse = new SysLogsWarehouse();
                    logsWarehouse.setOutInWarehouse(1);
                    logsWarehouse.setFstashId(sysTransport.getFsid());
                    logsWarehouse.setStashId(sysTransport.getSid());
                    logsWarehouse.setCreateDate(new Date());
                    logsWarehouse.setInFromTo(sysTransport.getEndAddress());
                    logsWarehouse.setOutInSum(addtrop.getNum());
                    logsWarehouse.setOutInGoods(sysTransport.getCname());
                    //获取登录人
                    Map getuser = getuser();
                    logsWarehouse.setOutInUser(getuser.get("name").toString());
                    logsWarehouseService.save(logsWarehouse);
                }
            }
            return  R.ok("运输成功");
        }
        return R.fail("运输失败");
    }
    /**
     * 获取登录用户
     */
    private Map getuser() {
        String token = request.getHeader("token");
        JWT of = JWT.of(token);
        String name = (String) of.getPayload("name");
        Integer id = (Integer) of.getPayload("id");
        Map<String, String> map = new HashMap<>();
        map.put("id",id+"");
        map.put("name",name);
        return map;
    }

    private SysTransport addtrop(SysTransport sysTransport) {
        SysTransport sysTransport1 = new SysTransport();
        //结束地址
        SysTradesman tradesman = tradesmanService.getById(sysTransport.getPid());
        sysTransport1.setEndAddress(tradesman.getAddress());
        sysTransport1.setEndIp(tradesman.getIp());
        sysTransport1.setStatus("0");
        //开始地址
        SysStashs stashs = sysStashsService.getById(sysTransport.getFsid());
        sysTransport1.setStartAddress(stashs.getAddress());
        sysTransport1.setStartIp(stashs.getIp());
        sysTransport1.setCname(sysTransport.getCname());
        sysTransport1.setNum(sysTransport.getNum());
        sysTransport1.setFsid(sysTransport.getFsid());
        sysTransport1.setPid(sysTransport.getPid());
        sysTransport1.setHaulerName(sysTransport.getHaulerName());
        sysTransport1.setSid(sysTransport.getSid());
        System.err.println(sysTransport);
        return sysTransport1;
    }

    /**
     * 更改物流状态
     */
    @RequestMapping("changeStatus")
    @Transactional
    public R changeStatus(@RequestBody SysTransportTradesman sysTransportTradesman){
        System.err.println(sysTransportTradesman);
        if (sysTransportTradesman!=null) {
            SysTransport transport = transportService.getById(sysTransportTradesman.getSid());
            if (transport != null) {
                if (transport.getStatus().equals("0")) {
                    transport.setStatus("1");
                    System.err.println(transport);
                } else {
                    transport.setStatus("2");
                    System.err.println(transport);
                    transport.setCompletionTime(new Date());
                    transportTradesmanService.save(sysTransportTradesman);
                }
                boolean update = transportService.updateById(transport);
                return  update?R.ok("出库成功"):R.fail("出库失败");
            }
        }
        return R.fail("出库失败");
    }

    /**
     * sys_tradesman
     * 查询零售商
     */
    @RequestMapping("list")
    public R list(){
        List<SysTradesman> list = tradesmanService.list();
        return R.ok(list);
    }

    /**
     * 零售商列表
     */
    @RequestMapping("tList")
    public R tList(){
        List<SysTransportTradesman> list = transportTradesmanService.getlist();
        return R.ok(list);
    }

    /**
     * 作物追溯
     * @param cropId
     * @return
     */

    @RequestMapping("/gettListbyid")
    public R gettListbyid(Integer cropId){
        List<SysTransportTradesman> list = transportTradesmanService.getlistbyid(cropId);
        return R.ok(list);
    }


    /**
     * 添加gps 信息 通过tdengine
     */
    @RequestMapping("/saveTdtrance")
    public R saveTdtrance(@RequestBody Tdtrance tdtrance){
        boolean save = tdtranceService.save(tdtrance);
        return save ? R.ok() : R.fail();
    }
    @RequestMapping("/hlist")
    public R hlist(){
        List<SysTransport> list = transportService.list();
        List<Tdtrance> list1 = tdtranceService.list();
        System.out.println(list1);
        System.out.println(list);
        return R.ok(list);
    }

}
